﻿#include "common.h"
#include "RecordingWindow.h"

RecordingWindow::RecordingWindow(QWidget *parent)
	: QWidget(parent)
	, ffmpegRecording(new FFmpegRecording(this))
{
	ui.setupUi(this);

	ui.lineEdit_path->setText(QDir::currentPath() + "/recordings");

	ui.pushButton_start->setEnabled(false);

	// 获取默认 Label 样式
	defaultLabelColor = ui.label_mode->palette().color(QPalette::WindowText);

	// 设置默认按钮颜色
	std::vector<QPushButton*> buttons = {
		ui.pushButton_microphone,
		ui.pushButton_speaker,
		ui.pushButton_both,
		ui.pushButton_start,
		ui.pushButton_pause,
		ui.pushButton_stop
	};
	for (auto button : buttons) {
		//button->setAutoFillBackground(true);
		button->setStyleSheet(buttonStyleSheet);
	}

	connect(ui.toolButton_path, SIGNAL(clicked()), this, SLOT(selectPathSlot()));

	connect(ui.pushButton_microphone, SIGNAL(clicked()), this, SLOT(inMicrophoneSlot()));
	connect(ui.pushButton_speaker, SIGNAL(clicked()), this, SLOT(inSpeakerSlot()));
	connect(ui.pushButton_both, SIGNAL(clicked()), this, SLOT(inBothSlot()));

	connect(ui.pushButton_start, SIGNAL(clicked()), this, SLOT(startRecordingSlot()));
	connect(ui.pushButton_pause, SIGNAL(clicked()), this, SLOT(pauseRecordingSlot()));
	connect(ui.pushButton_stop, SIGNAL(clicked()), this, SLOT(stopRecordingSlot()));
}

RecordingWindow::~RecordingWindow()
{}


void RecordingWindow::selectPathSlot()
{
	QFileDialog dialog(this);
	dialog.setFileMode(QFileDialog::Directory);
	dialog.setDirectory(QDir::currentPath());
	if (dialog.exec()) {
		QString path = dialog.selectedFiles()[0];
		if (path.isEmpty())
			return;
		ui.lineEdit_path->setText(path);
	}
}

void RecordingWindow::inMicrophoneSlot()
{
	QPalette palette = ui.label_mode->palette();
	if (ui.pushButton_speaker->isChecked())
		if (ui.pushButton_microphone->isChecked())
			ui.label_mode->setText(u8"双文件录制");
		else
			ui.label_mode->setText(u8"仅扬声器");
	else if (ui.pushButton_microphone->isChecked())
		ui.label_mode->setText(u8"仅麦克风");
	else {
		ui.label_mode->setText(u8"没有选择录制设备");
		palette.setColor(QPalette::WindowText, defaultLabelColor); // 恢复颜色
		ui.pushButton_start->setEnabled(false);
		goto end;
	}
	palette.setColor(QPalette::WindowText, QColor(255, 192, 203)); // 设置文本颜色为粉色
	ui.pushButton_start->setEnabled(true);
end:
	ui.label_mode->setPalette(palette);
	ui.pushButton_both->setChecked(false);
}

void RecordingWindow::inSpeakerSlot()
{
	QPalette palette = ui.label_mode->palette();
	if (ui.pushButton_microphone->isChecked())
		if (ui.pushButton_speaker->isChecked())
			ui.label_mode->setText(u8"双文件录制");
		else
		ui.label_mode->setText(u8"仅麦克风");
	else if (ui.pushButton_speaker->isChecked())
		ui.label_mode->setText(u8"仅扬声器");
	else {
		ui.label_mode->setText(u8"没有选择录制设备");
		palette.setColor(QPalette::WindowText, defaultLabelColor); // 恢复颜色
		ui.pushButton_start->setEnabled(false);
		goto end;
	}
	palette.setColor(QPalette::WindowText, QColor(255, 192, 203)); // 设置文本颜色为粉色
	ui.pushButton_start->setEnabled(true);
end:
	ui.label_mode->setPalette(palette);
	ui.pushButton_both->setChecked(false);
}

void RecordingWindow::inBothSlot()
{
	QPalette palette = ui.label_mode->palette();
	if (ui.pushButton_both->isChecked()) {
		ui.label_mode->setText(u8"混合录制");
		palette.setColor(QPalette::WindowText, QColor(255, 192, 203)); // 设置文本颜色为粉色
		ui.pushButton_start->setEnabled(true);
	}
	else {
		ui.label_mode->setText(u8"没有选择录制设备");
		palette.setColor(QPalette::WindowText, defaultLabelColor); // 恢复颜色
		ui.pushButton_start->setEnabled(false);
	}
	ui.label_mode->setPalette(palette);
	ui.pushButton_microphone->setChecked(false);
	ui.pushButton_speaker->setChecked(false);
}

void RecordingWindow::startRecordingSlot()
{
	/*
	// 文字判断虽然可读性高，但是维护性差
	if (ui.pushButton_start->text() == u8"录制中")
		return;
	if (ui.pushButton_start->text() == u8"继续录制") {
		ffmpegRecording->resume_record();
		return;
	}
	*/
	if (ffmpegRecording->is_recording() && !ffmpegRecording->is_paused()) // 持续录音中
		return;

	// 设置 start 按钮的背景色为粉色，设置文字提示
    QPalette palette;
    palette.setColor(QPalette::Button, QColor(255, 192, 203));
    ui.pushButton_start->setPalette(palette);
    ui.pushButton_start->setAutoFillBackground(true);
	ui.pushButton_start->setText(u8"录制中");

    // 将 pause 按钮的背景色设置为默认
    ui.pushButton_pause->setPalette(QPalette());
    ui.pushButton_pause->setAutoFillBackground(false);
	ui.pushButton_pause->setText(u8"暂停录制");

    // 将 stop 按钮的背景色设置为默认
    ui.pushButton_stop->setPalette(QPalette());
    ui.pushButton_stop->setAutoFillBackground(false);
	ui.pushButton_stop->setText(u8"停止");

	// 设置选择不可用
	enableSelection(false);

	if (ffmpegRecording->is_recording() && ffmpegRecording->is_paused()) { // 录音中，但是暂停了
		ffmpegRecording->resume_record();
		return;
	}

	// 录制模式判断
	if (ui.pushButton_microphone->isChecked() && ui.pushButton_speaker->isChecked()) {
		currentInputType = MyIODeviceType::MicrophoneAndSpeaker; // 混合录制，麦克风和扬声器音频录制混合到一个文件
	}
	else if (ui.pushButton_both->isChecked()) {
		currentInputType = MyIODeviceType::TwoFile; // 双文件录制
	}
	else if (ui.pushButton_microphone->isChecked()) {
		currentInputType = MyIODeviceType::Microphone; // 仅麦克风
	}
	else if (ui.pushButton_speaker->isChecked()) {
		currentInputType = MyIODeviceType::Speaker; // 仅扬声器
	}
	else {
		// 未选择设备，理论上不会走到这里
		QMessageBox::warning(this, u8"警告", u8"没有选择录制设备");
		return;
	}

	// 文件路径和文件名
	QString dir = ui.lineEdit_path->text();
	bool okpath = QDir().mkpath(dir); // 确保目录存在，存在会忽略，如果不存在则创建
	if (!okpath) {
		QMessageBox::warning(this, u8"警告", u8"创建目录失败，请检查路径是否正确");
		return;
	}
	QString baseName = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss");
	QString file1 = dir + "/microphone_" + baseName + ".aac";
	QString file2 = dir + "/loudspeaker_" + baseName + ".aac";

	int sampleRate = ui.comboBox_sample_rate->currentText().toInt();
	int channels = ui.comboBox_channels->currentText().toInt();

	// 启动录制
	std::string file1_str = file1.toUtf8().constData();
	std::string file2_str = file2.toUtf8().constData();
	if (currentInputType == MyIODeviceType::TwoFile) {
		// 双文件录制，分别录制麦克风和扬声器，并保存到两个文件中
		ffmpegRecording->start_record(file1_str, sampleRate, channels, currentInputType, file2_str);
	}
	else if (currentInputType == MyIODeviceType::MicrophoneAndSpeaker) {
		QString file3 = dir + "/mixed_" + baseName + ".aac";
		std::string file3_str = file3.toUtf8().constData();
		ffmpegRecording->start_record(file3_str, sampleRate, channels, currentInputType);
	}
	else if (currentInputType == MyIODeviceType::Microphone) {
		ffmpegRecording->start_record(file1_str, sampleRate, channels, currentInputType);
	}
	else if (currentInputType == MyIODeviceType::Speaker) {
		ffmpegRecording->start_record(file2_str, sampleRate, channels, currentInputType);
	}
	else {
		// 理论上不会走到这里
		QMessageBox::warning(this, u8"警告", u8"没有选择录制设备，请重新选择");
		return;
	}
}

void RecordingWindow::pauseRecordingSlot()
{
	if (ui.pushButton_pause->text() == u8"暂停中")
		return;

	// 设置 pause 按钮的背景色为粉色，设置文字提示
	QPalette palette;
	palette.setColor(QPalette::Button, QColor(255, 192, 203));
	ui.pushButton_pause->setPalette(palette);
	ui.pushButton_pause->setAutoFillBackground(true);
	ui.pushButton_pause->setText(u8"暂停中");

	// 将 start 按钮的背景色设置为默认
	ui.pushButton_start->setPalette(QPalette());
	ui.pushButton_start->setAutoFillBackground(false);
	ui.pushButton_start->setText(u8"继续录制");

	// 将 stop 按钮的背景色设置为默认
	ui.pushButton_stop->setPalette(QPalette());
	ui.pushButton_stop->setAutoFillBackground(false);
	ui.pushButton_stop->setText(u8"停止");

	// 暂停录制
	if (ffmpegRecording) {
		ffmpegRecording->pause_record();
	}

}

void RecordingWindow::stopRecordingSlot()
{
	// 设置 stop 按钮的背景色为粉色
	QPalette palette;
	palette.setColor(QPalette::Button, QColor(255, 192, 203));
	ui.pushButton_stop->setPalette(palette);
	ui.pushButton_stop->setAutoFillBackground(true);
	ui.pushButton_stop->setText(u8"已停止");

	// 将 start 按钮的背景色设置为默认
	ui.pushButton_start->setPalette(QPalette());
	ui.pushButton_start->setAutoFillBackground(false);
	ui.pushButton_start->setText(u8"开始录制");

	// 将 pause 按钮的背景色设置为默认
	ui.pushButton_pause->setPalette(QPalette());
	ui.pushButton_pause->setAutoFillBackground(false);
	ui.pushButton_pause->setText(u8"暂停录制");

	// 设置选择可用
	enableSelection(true);

	// 停止录制，保存文件
	if (ffmpegRecording) {
		ffmpegRecording->stop_record();
	}

}

void RecordingWindow::closeEvent(QCloseEvent* event)
{
	if (ffmpegRecording && ffmpegRecording->is_recording()) {
		QMessageBox::StandardButton reply;
		reply = QMessageBox::warning(this, u8"警告", u8"正在录制，是否停止录制并退出?", QMessageBox::Yes|QMessageBox::No);
		
		if (reply == QMessageBox::Yes) {
			// 停止录制，保存文件
			stopRecordingSlot();
			// 保存文件的逻辑可以根据具体需求添加
			
			// 关闭窗口
			cleanSource();
			emit closed();
			event->accept();
		}
		else {
			// 用户选择取消，忽略关闭事件
			event->ignore();
		}
	}
	else {
		// 如果没有录制，直接关闭窗口
		cleanSource();
		emit closed();
		event->accept();
	}
}

void RecordingWindow::enableSelection(bool flag)
{
	// 文件路径
	ui.lineEdit_path->setEnabled(flag);
	ui.toolButton_path->setEnabled(flag);

	// 录制设备选择
	ui.pushButton_microphone->setEnabled(flag);
	ui.pushButton_speaker->setEnabled(flag);
	ui.pushButton_both->setEnabled(flag);

	// 音频格式
	ui.comboBox_sample_rate->setEnabled(flag);
	ui.comboBox_channels->setEnabled(flag);
}

void RecordingWindow::cleanSource()
{
	if (ffmpegRecording) {
		delete ffmpegRecording;
		ffmpegRecording = nullptr;
	}
}